package com.course.servlet;

import com.course.entity.Student;
import com.course.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/xuesheng_personal_center")
public class XueshengPersonalCenterServlet extends HttpServlet {
    private final StudentService studentService = new StudentService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        Student student = (Student) session.getAttribute("student");

        if (student == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        request.setAttribute("student", student);
        request.getRequestDispatcher("/student/xuesheng_personal_center.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        HttpSession session = request.getSession();
        Student student = (Student) session.getAttribute("student");

        if (student == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        String studentName = request.getParameter("studentName");
        String password = request.getParameter("password");
        String contactInfo = request.getParameter("contactInfo");

        student.setName(studentName);
        student.setPassword(password);
        student.setEmail(contactInfo);

        boolean success = studentService.updateStudent(student);

        if (success) {
            session.setAttribute("student", student); // Update session with new info
            request.setAttribute("successMessage", "个人信息更新成功！");
        } else {
            request.setAttribute("errorMessage", "个人信息更新失败，请重试。");
        }
        doGet(request, response);
    }
} 